"""
封装request 针对不同请求的方法封装的request
"""

import requests

from util.report import log_tool
from util.report.decorators_tool import logs
import time
from urllib3 import encode_multipart_formdata


@logs
def get(url, params=None, headers=None, cookies=None):
    """get请求,获取接口的响应数据

    :param url:  ip host
    :param params: 请求的键值对参数
    :param headers: 请求头信息
    :param cookies: 请求的cookies

    :return: 返回响应信息
    """
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        print(url)
    try:
        response = requests.get(url=url, params=params, headers=headers, cookies=cookies)
    except Exception as e:
        log_tool.error('%s%s' % ('Exception url: ', url))
        log_tool.error(e)
        return ()
    # time_consuming = response.elapsed.microseconds / 1000
    # log_tool.info('----请求用时: %s 秒数' % time_consuming)
    return response

@logs
def delete(url=None, **kwargs):
    """delete请求,获取删除的接口响应数据

    :param url:  ip host
    :param kwargs:
        | headers: 请求头信息
        | cookies: 请求的cookies

    :return: 返回响应信息
    """
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        print(url)
    try:
        response = requests.delete(url=url,**kwargs)

    except Exception as e:
        log_tool.error('%s%s' % ('Exception url: ', url))
        log_tool.error(e)
        return ()
    # time_consuming = response.elapsed.microseconds / 1000
    # log_tool.info('----请求用时: %s 秒数' % time_consuming)
    return response

@logs
def post(url, params=None,data=None, files=None,json=None,  headers=None,  cookies=None):
    """ post请求,用来新增数据

    :param url: ip+host+path
    :param params: 字典或者字节序列，作为参数增加到URL中
    :param data: 可传字符串,字典,元祖
    :param files: 文件路径
    :param json: json参数会自动将字典类型的对象转换为json格式
    :param headers: 请求头信息
    :param cookies: cookies

    :return: 返回响应信息
    """
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        print(url)
    try:
        response = requests.post(url, data=data, files=files, params=params, headers=headers, json=json,
                                 cookies=cookies)
    except Exception as e:
        log_tool.error('%s%s' % ('Exception url: ', url))
        log_tool.error(e)
        return ()
    # time_consuming为响应时间，单位为毫秒
    # time_consuming = response.elapsed.microseconds / 1000
    # log_tool.info('----请求用时: %s 秒数' % time_consuming)
    return response


@logs
def post_data(url, data=None, headers=None, cookies=None):
    """针对post data格式的数据定义的方法,只支持data格式的数据

    :param url: ip+host+path
    :param data: 可传字符串,字典,元祖
    :param headers: 请求头信息
    :param cookies: cookies

    :return: 返回响应信息
    """
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        print(url)
    try:
        response = requests.post(url, data=data, headers=headers, cookies=cookies)
    except Exception as e:
        log_tool.error('%s%s' % ('Exception url: ', url))
        log_tool.error(e)
        return ()
    # time_consuming为响应时间，单位为毫秒
    # time_consuming = response.elapsed.microseconds / 1000
    # log_tool.info('----请求用时: %s 秒数' % time_consuming)
    return response


@logs
def post_params(url, params=None, headers=None, cookies=None):
    """针对post params格式定义的方法 只支持params传参

    :param url: ip+host+path
    :param params: 字典或者字节序列，作为参数增加到URL中
    :param headers: 请求头
    :param cookies: cookies

    :return: 响应数据
    """
    headers={}
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        print(url)
    try:
        response = requests.post(url, params=params, headers=headers, cookies=cookies)
    except Exception as e:
        log_tool.error('%s%s' % ('Exception url: ', url))
        log_tool.error(e)
        return ()
    # time_consuming为响应时间，单位为毫秒
    # time_consuming = response.elapsed.microseconds / 1000
    # log_tool.info('----请求用时: %s 秒数' % time_consuming)
    return response

# @logs
def post_json(url, json=None, headers=None, cookies=None):
    """针对post json格式的输出封装

    :param url: ip+host+path
    :param json: 支持字典或者json格式的数据传参
    :param headers: 请求头
    :param cookies: cookie

    :return: 返回响应数据
    """
    if headers == None:
        headers={}
    headers['content-type']='application/json;;charset=UTF-8'
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        print(url)
    try:
        response = requests.post(url, headers=headers, json=json,cookies=cookies)
    except Exception as e:
        log_tool.error('%s%s' % ('Exception url: ', url))
        log_tool.error(e)
        return ()
    # time_consuming为响应时间，单位为毫秒
    # time_consuming = response.elapsed.microseconds / 1000
    # log_tool.info('----请求用时: %s 秒数' % time_consuming)
    return response


@logs
def post_file(url, files=None, headers=None, cookies=None):
    """针对post file格式的函数

    :param url: ip+host+path
    :param files: 文件路径
    :param headers: 请求头
    :param cookies:  cookies

    :return: 返回响应数据
    """
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        print(url)
    try:
        response = requests.post(url=url, files=files, headers=headers, cookies=cookies)
    except Exception as e:
        log_tool.error('%s%s' % ('Exception url: ', url))
        log_tool.error(e)
        return ()
    # time_consuming为响应时间，单位为毫秒
    # time_consuming = response.elapsed.microseconds / 1000
    # log_tool.info('----请求用时: %s 秒数' % time_consuming)

    return response



@logs
def put(url, data, header=None, cookies=None):
    """针对数据修改封装的函数

    :param url: ip+host+path
    :param data: 可传字符串,字典,元祖
    :param header: 请求头
    :param cookies: cookies

    :return: 响应数据
    """
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        log_tool.debug(url)

    try:
        if data is None:
            response = requests.put(url=url, headers=header, cookies=cookies)
        else:
            response = requests.put(url=url, params=data, headers=header, cookies=cookies)

    except Exception as e:
        log_tool.error('%s%s' % ('RequestException url: ', url))
        log_tool.error(e)
        return ()
    # time_consuming = response.elapsed.microseconds / 1000
    # log_tool.info('----请求用时: %s 秒数' % time_consuming)

    return response


def down_big_file(src_url, local_file,**kwargs):
    """下载文件接口并写入指定目录

    :param src_url: ip+host+path
    :param local_file: 下载保存的文件路径地址
    :param kwargs:
        | headers: 请求头信息
    """
    print('%s\n --->>>\n  %s' % (src_url, local_file))
    start_time = time.time()

    # with requests.get(src_url, stream=True,**kwargs) as r:
    with requests.get(src_url,params=None,**kwargs) as r:
        contentLength = int(r.headers['content-length'])
        line = 'content-length: %dB/ %.2fKB/ %.2fMB'
        line = line % (contentLength, contentLength / 1024, contentLength / 1024 / 1024)
        print(line)
        print('正在下载中..............')
        downSize = 0
        with open(local_file, 'wb') as f:
            for chunk in r.iter_content(8192):
                if chunk:
                    f.write(chunk)
                downSize += len(chunk)
                line = '%d KB/s - %.2f MB， 共 %.2f MB'
                line = line % (
                    downSize / 1024 / (time.time() - start_time), downSize / 1024 / 1024, contentLength / 1024 / 1024)
                print(line, end='\r')
                if downSize >= contentLength:
                    break
        timeCost = time.time() - start_time
        line = '共耗时: %.2f s, 平均速度: %.2f KB/s'
        line = line % (timeCost, downSize / 1024 / timeCost)
        print(line)


def copy_github_file(url, save_name):
    resp = get(url)
    body = resp.text
    with open(save_name, 'w', encoding='utf-8') as file:
        file.write(body)


def post_upload_file(url, header, file_path):
    """post请求入参使用文件上传"""
    data = {'file': (file_path.split('/')[-1], open(file_path, 'rb').read())}
    boundary = header['Content-Type'].split('=')[-1]  # 使用配置文件中headers定义的boundary
    encode_data = encode_multipart_formdata(data,
                                            boundary=boundary)  # encode_multipart_formdata不传入boundary会使用uuid4()自动生成，故需进行替换
    response = requests.post(url, headers=header, data=encode_data[0])
    return response
